package com.echo.fm.content.news;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.echo.fm.content.news.model.News;
import com.echo.fm.content.news.model.NewsDto;
import com.echo.util.ErrorException;
import com.echo.util.ResultUtils;

/**
 * 
 * @author Administrator 数据库dao层
 *
 */

@Repository("newsPersistence")
public class DAONewsPersistenceImpl implements INewsPersistence {
	@Autowired
	@Qualifier("sessionFactory")
	SessionFactory sessionFactory;

	/**
	 * 添加新闻
	 */

	public void addNews(News news) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			session.save(news);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 删除新闻
	 */

	public void deleteNews(News news) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			session.delete(news);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 
	 * 查找新闻
	 */

	public News searchNewsById(String id) throws ErrorException {
		Session session = null;
		try {
			session = sessionFactory.openSession();
			return (News) session.get(News.class, id);
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	/**
	 * 修改新闻
	 */

	public void updateNewsById(News news) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			session.update(news);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	public List<NewsDto> listSearchNews(String title, Long startTimeL, Long endTimeL, Integer status, Integer newsType,
			Integer max, Integer fristNumber) throws ErrorException {

		Session session = null;
		try {
			session = sessionFactory.openSession();

			StringBuffer stringBuffer = new StringBuffer();
			String query = "select t1.id,t1.title,t1.url,t1.timeL,t1.sort,t1.read_count,t1.status,t1.oper,t2.title as typeTitle from news as t1 left join newstype as t2 on t1.news_type = t2.id where 1=1";
			stringBuffer.append(query);
			if (title != null) {
				String titleQuery = " and t1.title like '%" + title + "%'";
				stringBuffer.append(titleQuery);
			}

			if ((startTimeL != null && startTimeL != 0L) && (endTimeL != null && endTimeL != 0L)) {
				String datequery = " and t1.timeL between %d and %d ";
				stringBuffer.append(String.format(datequery, startTimeL, endTimeL));
			}
			if (status != null) {
				String statusQuery = " and t1.status = %d";
				stringBuffer.append(String.format(statusQuery, status));
			}
			if (newsType != null) {
				String typeQuery = " and t1.news_type = %d";
				stringBuffer.append(String.format(typeQuery, newsType));
			}
			@SuppressWarnings("unchecked")
			List<Object[]> newsList = session.createSQLQuery(stringBuffer.toString()).setMaxResults(max).list();
			List<NewsDto> newsDtoList = new ArrayList<NewsDto>();

			for (Object[] objects : newsList) {
				NewsDto dto = new NewsDto();
				dto.setId((String) objects[0]);
				dto.setTitle((String) objects[1]);
				dto.setUrl((String) objects[2]);
				dto.setTimeL(((BigInteger) objects[3]).longValue());
				dto.setSort((Double) objects[4]);
				dto.setReadCount((Integer) objects[5]);
				dto.setStatus((Integer) objects[6]);
				dto.setOper((String) objects[7]);
				dto.setTypeTitle((String) objects[8]);

				newsDtoList.add(dto);
			}
			return newsDtoList;
		} catch (HibernateException e) {
			e.printStackTrace();
			return null;
		}

	}

	// public List<News> listSearchNews(String title, Long startTimeL, Long
	// endTimeL, Integer status, Integer newsType,
	// Integer max, Integer fristNumber) throws ErrorException {
	// Session session = null;
	// try {
	// session = sessionFactory.openSession();
	// StringBuffer stringBuffer = new StringBuffer();
	// String query = "from News where 1=1 ";
	// stringBuffer.append(query);
	// if (title != null) {
	// String titleQuery = "and title like '%" + title + "%'";
	// stringBuffer.append(titleQuery);
	// }
	//
	// if ((startTimeL != null && startTimeL != 0L) && (endTimeL != null &&
	// endTimeL != 0L)) {
	// String datequery = " and timeL between %d and %d ";
	// stringBuffer.append(String.format(datequery, startTimeL, endTimeL));
	// }
	// if (status != null) {
	// String statusQuery = " and status = %d";
	// stringBuffer.append(String.format(statusQuery, status));
	// }
	// if (newsType != null) {
	// String typeQuery = " and news_type = %d";
	// stringBuffer.append(String.format(typeQuery, newsType));
	// }
	//
	// @SuppressWarnings("unchecked")
	// List<News> newsList = (List<News>)
	// session.createQuery(stringBuffer.toString()).setMaxResults(max).list();
	// return newsList;
	//
	// } catch (Exception e) {
	// e.printStackTrace();
	// throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
	// } finally {
	// if (session != null)
	// session.close();
	// }
	// }

}
